﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BadHabit.Factory.Controls {

    /// <summary>
    /// Interaction logic for ArtifactListBox.xaml
    /// </summary>
    public partial class ArtifactListBox : ListBox {


        
        
        public string BacklogItemUId { get; set;}

        

        internal static readonly DependencyProperty TaskUIdProperty =
            DependencyProperty.Register("TaskUId", typeof(string), typeof(ArtifactListBox), null);
        public string TaskUId {
            get {
                return (string)GetValue(TaskUIdProperty);
            }
            set {
                SetValue(TaskUIdProperty, value);
            }
        }

        internal static readonly DependencyProperty ProjectProperty =
            DependencyProperty.Register("Project", typeof(Data.ProjectDataSet.ProjectRow), typeof(ArtifactListBox), null);
        public Data.ProjectDataSet.ProjectRow Project {
            get {
                return (Data.ProjectDataSet.ProjectRow)GetValue(ProjectProperty);
            }
            set {
                SetValue(ProjectProperty, value);
            }
        }

        public Predicate<Object> IsInFilter { get; set; }

        public ArtifactListBox() {
            InitializeComponent();
        }
                

        /// <summary>
        /// Load the artifacts
        /// </summary>        
        public void LoadArtifacts() {
            Data.TaskDataSet dsTail = new BadHabit.Factory.Data.TaskDataSet();
            
            
            if (Project == null)
                return;
            
            try {                
                if (BacklogItemUId == null)
                    dsTail.Merge(Client.Service.RetriveArtifactsByProjectUId(Project.ProjectUId, Project.Category));
                else
                    dsTail.Merge(Client.Service.RetriveArtifactsByBacklogItemUId(BacklogItemUId, Project.Category));
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_READ_ARTIFACTS);
            }

            System.Windows.Data.ListCollectionView artifactView = new System.Windows.Data.ListCollectionView(dsTail.TaskTail.DefaultView);
            ItemsSource = artifactView;

            artifactView.GroupDescriptions.Add(new PropertyGroupDescription("ArtifactGroup"));
            artifactView.SortDescriptions.Add(new System.ComponentModel.SortDescription("ActivityOrder", System.ComponentModel.ListSortDirection.Ascending));
            artifactView.SortDescriptions.Add(new System.ComponentModel.SortDescription("ArtifactName", System.ComponentModel.ListSortDirection.Ascending));

            if (IsInFilter != null)
                artifactView.Filter = IsInFilter;
            else
                artifactView.Filter = IsInFilterTaskUId;


            SelectedItem = null;
            
        }

        protected void HandleDoubleClick(object sender, MouseButtonEventArgs e) {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(((ListBoxItem)sender).DataContext);
            if (tail == null)
                return;
            Helper.OpenOSWindow(MountArtifactURL(tail));
        }


        private string MountArtifactURL(Data.TaskDataSet.TaskTailRow tail) {

            if (!tail.IsSourceControled)
                return tail.ArtifactPath;


            string url = Client.SourceControlViewUrl.ToLower();
            url = url.Replace("$repositoryurl$", tail.RepositoryUrl);
            url = url.Replace("$artifactrevision$", tail.ArtifactRevision.ToString());
            url = url.Replace("$artifactpath$", tail.ArtifactPath);


            return url;
        }

        private void openMenuItem_Click(object sender, RoutedEventArgs e) {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(this.SelectedItem);
            if (tail == null)
                return;

            Helper.OpenOSWindow(MountArtifactURL(tail));
        }

        private void removeTailMenuItem_Click(object sender, RoutedEventArgs e) {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(this.SelectedItem);
            if (tail == null)
                return;
            
            try {
                Client.Service.RemoveTaskTailFromBacklogItem(tail.ArtifactPath, BacklogItemUId);
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_REMOVE_TAIL);
                return;
            }

            System.Windows.Data.ListCollectionView artifactView = this.ItemsSource as System.Windows.Data.ListCollectionView;
            artifactView.Remove(artifactView.CurrentItem);


            
        }

        private bool IsInFilterTaskUId(object obj) {
            System.Data.DataRowView tail = obj as System.Data.DataRowView;
            if (tail == null)
                return false;

            if (TaskUId != null) {
                if (!tail["TaskUId"].ToString().Equals(TaskUId))
                    return false;
            }

            return true;

        }

        private void listBox_Drop(object sender, DragEventArgs e) {
            IDataObject o = e.Data;                        
            string[] fileName = o.GetData("FileNameW") as string[];
            if (fileName == null)
                return;

            TaskViewerBase.AddTaskMaterial(TaskUId, Project.ProjectDocBase, fileName, false);

            LoadArtifacts();
            
        }

    }
}
